/*
 * Copyright 2011 Michael Nitsche
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package de.abcsolutions.g5.net.tcp;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import de.abcsolutions.g5.base.event.A_HasListeners;
import de.abcsolutions.g5.base.event.I_Listener;

/**
 * @author Michael Nitsche
 * 02.03.2011	Converted to G5
 *
 * TCP-Client
 */
public class TCP_Client extends A_HasListeners {

	private enum EVENT { TIMEOUT, EXCEPTION };
	private final String host;
	private final int port;


	public TCP_Client(String host, int port) throws IOException {
		this.host=host;
		this.port=port;
	}


	public TCP_Connection verbinde() {
		try {
			Socket socket = new Socket(host, port);
			socket.setSoTimeout(60000); //FIXME
			return new TCP_Connection(socket, false);
		}
		catch(SocketTimeoutException e) {
//			Timeout: 60000 = 1 Minute
			this.listenerStart(EVENT.TIMEOUT, e);
			e.printStackTrace();
		}
		catch(UnknownHostException e) {
			this.listenerStart(EVENT.EXCEPTION, e);
			e.printStackTrace();
		}
		catch(IOException e) {
			this.listenerStart(EVENT.EXCEPTION, e);
			e.printStackTrace();
		}
		return null;
	}

	public void addListenerTimeOut(I_Listener<SocketTimeoutException> z) {
		this.listenerAdd(EVENT.TIMEOUT, z);
	}

	public void addListenerException(I_Listener<IOException> z) {
		this.listenerAdd(EVENT.EXCEPTION, z);
	}

}

